package cm367;

import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

@ManagedBean
public class LoginRequest {
	private String name;
	private String password;
	
	@ManagedProperty(value="#{userService}")
	private UserService userService;
	
	@ManagedProperty(value="#{loggedInUser}")
	private LoggedInUser loggedInUser;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String login(){
		if (userService.validateUser(name, password)){
			
			loggedInUser.setUser(userService.findUserByName(name));
			
			if (loggedInUser.getOriginalViewId() != null){
				FacesContext context = FacesContext.getCurrentInstance();
				ViewHandler viewHandler = context.getApplication().getViewHandler();
				UIViewRoot viewRoot = viewHandler.createView(context, loggedInUser.getOriginalViewId());
				context.setViewRoot(viewRoot);
				return null;
			}else{
				if (loggedInUser.getUser().getRole()=="Admin")
					return "set";
				else
					return "success";
			}
		}else{
			return "fail";
		}
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public LoggedInUser getLoggedInUser() {
		return loggedInUser;
	}
	public void setLoggedInUser(LoggedInUser loggedInUser) {
		this.loggedInUser = loggedInUser;
	}
	
}
